﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using BartonExtension;
using System.Web.Script.Services;
using ResponseObject;
using SqlServerWrapper;
using System.Data.SqlClient;
using System.Data;
using Model;

namespace WebSrvs.NET
{
    /// <summary>
    /// ZK_BackEndService 的摘要说明
    /// </summary>
    [System.Web.Script.Services.ScriptService]
    [WebService(Namespace = "http://zker.hk/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
    // [System.Web.Script.Services.ScriptService]
    public class ZK_GeneralService : System.Web.Services.WebService
    {

        [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public string catalogs(string lan_tag)
        {
            ZKResponse response = new ZKResponse();
            string connStr = SqlConnectionManager.GetConnStrFromConfig();
            using (SqlConnection conn = SqlConnectionManager.CreateSqlConnection(connStr))
            {
                conn.Open();
                using (SqlCommand cmd = SqlCommandManager.Create(conn, CommandType.StoredProcedure))
                {
                    cmd.CommandText = "proc_get_catalogs";
                    cmd.Parameters.Add("@language_tag", SqlDbType.NVarChar).Value = lan_tag;
                    try
                    {
                        using (SqlDataReader dr = cmd.ExecuteReader())
                        {
                            DataTable dt = new DataTable("catalogs");
                            dt.Load(dr);
                            if (dt.Rows.Count > 0)
                            {
                                List<Catalog> catalogs = new List<Catalog>();
                                foreach (DataRow row in dt.Rows)
                                {
                                    Catalog catalog = new Catalog()
                                    {
                                        ID = row["ID"].toInt32().Value,
                                        code = row["code"].ToString(),
                                        title = row["title"].ToString(),
                                        title_en = row["title_en"].ToString(),
                                        parent_code = row["parent_code"].ToString(),
                                        layer = row["layer"].toInt32().Value
                                    };
                                    catalogs.Add(catalog);
                                }
                                response.userinfo = catalogs;
                            }
                            else
                            {
                                response.isProcessSuccess = false;
                                response.errCode = ErrorCodes.CODE_ERR_ON_REQ_CATALOG_LIST_ZERO_RESULT_SET;
                                response.errMsg = ErrorMsgs.MSG_ERR_ON_REQ_CATALOG_LIST_ZERO_RESULT_SET;
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        response.isProcessSuccess = false;
                        response.errCode = ErrorCodes.CODE_ERR_INTERNAL_ERR;
                        response.errMsg = ex.Message;
                    }
                }
            }
            return response.ToJson();
        }

        [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public string brands(int page_index, int page_capacity, string lan_tag)
        {
            ZKResponse response = new ZKResponse();
            string connStr = SqlConnectionManager.GetConnStrFromConfig();
            using (SqlConnection conn = SqlConnectionManager.CreateSqlConnection(connStr))
            {
                conn.Open();
                using (SqlCommand cmd = SqlCommandManager.Create(conn, CommandType.StoredProcedure))
                {
                    cmd.CommandText = "proc_get_brands";
                    cmd.Parameters.Add("@page_index", SqlDbType.Int).Value = page_index;
                    cmd.Parameters.Add("@page_capacity", SqlDbType.Int).Value = page_capacity;
                    cmd.Parameters.Add("@language_tag", SqlDbType.NVarChar).Value = lan_tag;
                    try
                    {
                        using (SqlDataReader dr = cmd.ExecuteReader())
                        {
                            DataTable dt = new DataTable("brands");
                            dt.Load(dr);
                            if (dt.Rows.Count > 0)
                            {
                                List<Brand> brands = new List<Brand>();
                                foreach (DataRow row in dt.Rows)
                                {
                                    Brand brand = new Brand()
                                    {
                                        ID = row["ID"].toInt32().Value,
                                        code = row["code"].ToString(),
                                        title = row["title"].ToString(),
                                        title_origin = row["title_origin"].ToString(),
                                        level = row["level"].toFloat().Value,
                                        location = row["location"].ToString(),
                                        desc = row["desc"].ToString()
                                    };
                                    brands.Add(brand);
                                }
                                response.userinfo = brands;
                            }
                            else
                            {
                                response.isProcessSuccess = false;
                                response.errCode = ErrorCodes.CODE_ERR_ON_REQ_BRAND_LIST_ZERO_RESULT_SET;
                                response.errMsg = ErrorMsgs.MSG_ERR_ON_REQ_BRAND_LIST_ZERO_RESULT_SET;
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        response.isProcessSuccess = false;
                        response.errCode = ErrorCodes.CODE_ERR_INTERNAL_ERR;
                        response.errMsg = ex.Message;
                    }
                }
            }
            return response.ToJson();
        }

        [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public string stores(int page_num, int page_size)
        {
            ZKResponse response = new ZKResponse();
            string connStr = SqlConnectionManager.GetConnStrFromConfig();
            using (SqlConnection conn = SqlConnectionManager.CreateSqlConnection(connStr))
            {
                conn.Open();
                using (SqlCommand cmd = SqlCommandManager.Create(conn, CommandType.StoredProcedure))
                {
                    cmd.CommandText = "proc_get_stores";
                    cmd.Parameters.Add("@page_num", SqlDbType.Int).Value = page_num;
                    cmd.Parameters.Add("@page_size", SqlDbType.Int).Value = page_size;
                    try
                    {
                        using (SqlDataReader dr = cmd.ExecuteReader())
                        {
                            DataTable dt = new DataTable("data");
                            dt.Load(dr);
                            List<Store> storeCollection = new List<Store>();
                            foreach (DataRow row in dt.Rows)
                            {
                                //New Store
                                Store store = null;
                                //Find row index
                                int index = storeCollection.FindIndex(x =>
                                    {
                                        return row["ID"].toInt32().Value == x.ID;
                                    });
                                if (index != -1)
                                {
                                    Brand brand = new Brand()
                                    {
                                        ID = row["supported_brand_id"].toInt32().Value,
                                        level = row["level"].toInt32().Value,
                                        code = row["brand_code"].ToString(),
                                        title = row["title"].ToString(),
                                        title_origin = row["title_origin"].ToString(),
                                        location = row["location"].ToString(),
                                        desc = row["desc"].ToString(),
                                        lowPrice = row["lowBoundaryPrice"].toFloat().Value,
                                        topPrice = row["topBoundaryPrice"].toFloat().Value,
                                        topDiscount = row["top_bound_discount"].toFloat().Value,
                                        lowDiscount = row["low_bound_discount"].toFloat().Value,
                                        in_brand_catalog_ids = row["in_brand_catalogs_ids"].ToString()
                                    };
                                    storeCollection[index].brands.Add(brand);
                                    Catalog catalog = new Catalog()
                                    {
                                        ID = row["supported_catalog_id"].toInt32().Value,
                                        title = row["catalog_title"].ToString(),
                                        in_catalog_brand_ids = row["in_catalog_brands_ids"].ToString(),
                                        code = row["catalog_code"].ToString(),
                                        layer = row["layer"].toInt32().Value,
                                        parent_code = row["parent_code"].ToString(),
                                        title_en = row["catalog_title_en"].ToString()
                                    };
                                    storeCollection[index].catalogs.Add(catalog);
                                }
                                else
                                {
                                    store = Store.newStore();
                                    store.ID = row["ID"].toInt32().Value;
                                    store.title = row["title"].ToString();
                                    store.type = (StoreType)row["type"].toInt32().Value;
                                    store.frequency = row["frequency"].toFloat().Value;
                                    store.in_plaza_location = row["building_in"].ToString();
                                    store.location.ID = row["locationID"].toInt32().Value;
                                    store.location.region = row["region"].ToString();
                                    store.location.plaza = row["building"].ToString();
                                    store.location.addr = row["street_detail"].ToString();
                                    store.location.lat = row["lat"].toFloat().Value;
                                    store.location.lon = row["long"].toFloat().Value;
                                    Brand brand = new Brand()
                                    {
                                        ID = row["supported_brand_id"].toInt32().Value,
                                        level = row["level"].toInt32().Value,
                                        code = row["brand_code"].ToString(),
                                        title = row["title"].ToString(),
                                        title_origin = row["title_origin"].ToString(),
                                        location = row["location"].ToString(),
                                        desc = row["desc"].ToString(),
                                        lowPrice = row["lowBoundaryPrice"].toFloat().Value,
                                        topPrice = row["topBoundaryPrice"].toFloat().Value,
                                        topDiscount = row["top_bound_discount"].toFloat().Value,
                                        lowDiscount = row["low_bound_discount"].toFloat().Value,
                                        in_brand_catalog_ids = row["in_brand_catalogs_ids"].ToString()
                                    };
                                    store.brands.Add(brand);
                                    Catalog catalog = new Catalog()
                                    {
                                        ID = row["supported_catalog_id"].toInt32().Value,
                                        title = row["catalog_title"].ToString(),
                                        in_catalog_brand_ids = row["in_catalog_brands_ids"].ToString(),
                                        code = row["catalog_code"].ToString(),
                                        layer = row["layer"].toInt32().Value,
                                        parent_code = row["parent_code"].ToString(),
                                        title_en = row["catalog_title_en"].ToString()
                                    };
                                    store.catalogs.Add(catalog);
                                    storeCollection.Add(store);
                                }
                            }
                            if (storeCollection.Count == 0)
                            {
                                response.isProcessSuccess = false;
                                response.errCode = ErrorCodes.CODE_ERR_ON_REQ_STORE_LIST_ZERO_RESULT_SET;
                                response.errMsg = ErrorMsgs.MSG_ERR_ON_REQ_STORE_LIST_ZERO_RESULT_SET;
                            }
                            response.userinfo = storeCollection;
                        }
                    }
                    catch (Exception ex)
                    {
                        response.isProcessSuccess = false;
                        response.errCode = ErrorCodes.CODE_ERR_INTERNAL_ERR;
                        response.errMsg = ex.Message;
                    }
                }
            }
            return response.ToJson();
        }

        [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public string BrandInStoreExists(int store_id, int brand_id)
        {
            ZKResponse response = new ZKResponse();
            string connStr = SqlConnectionManager.GetConnStrFromConfig();
            using (SqlConnection conn = SqlConnectionManager.CreateSqlConnection(connStr))
            {
                conn.Open();
                using (SqlCommand cmd = SqlCommandManager.Create(conn, CommandType.StoredProcedure))
                {
                    cmd.CommandText = "proc_check_availability_on_brand";
                    cmd.Parameters.Add("@store_id", SqlDbType.Int).Value = store_id;
                    cmd.Parameters.Add("@brand_id", SqlDbType.Int).Value = brand_id;
                    cmd.Parameters.Add("@return", SqlDbType.Int).Direction = ParameterDirection.ReturnValue;
                    try
                    {
                        cmd.ExecuteNonQuery();
                        int returnVal = cmd.Parameters["@return"].Value.toInt32().Value;
                        if (returnVal > 0)
                        {
                            response.isProcessSuccess = false;
                            response.errCode = ErrorCodes.CODE_ERR_ON_BACKEND_LOCATION_EXIST;
                            response.errMsg = ErrorMsgs.MSG_ERR_ON_BACKEND_LOCATION_EXIST;
                        }
                    }
                    catch (Exception ex)
                    {
                        response.isProcessSuccess = false;
                        response.errCode = ErrorCodes.CODE_ERR_INTERNAL_ERR;
                        response.errMsg = ex.Message;
                    }
                }
            }
            return response.ToJson();
        }

        [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public string CatalogInStoreExists(int store_id, int catalog_id)
        {
            ZKResponse response = new ZKResponse();
            string connStr = SqlConnectionManager.GetConnStrFromConfig();
            using (SqlConnection conn = SqlConnectionManager.CreateSqlConnection(connStr))
            {
                conn.Open();
                using (SqlCommand cmd = SqlCommandManager.Create(conn, CommandType.StoredProcedure))
                {
                    cmd.CommandText = "proc_check_availability_on_brand";
                    cmd.Parameters.Add("@store_id", SqlDbType.Int).Value = store_id;
                    cmd.Parameters.Add("@catalog_id", SqlDbType.Int).Value = catalog_id;
                    cmd.Parameters.Add("@return", SqlDbType.Int).Direction = ParameterDirection.ReturnValue;
                    try
                    {
                        cmd.ExecuteNonQuery();
                        int returnVal = cmd.Parameters["@return"].Value.toInt32().Value;
                        if (returnVal > 0)
                        {
                            response.isProcessSuccess = false;
                            response.errCode = ErrorCodes.CODE_ERR_ON_BACKEND_LOCATION_EXIST;
                            response.errMsg = ErrorMsgs.MSG_ERR_ON_BACKEND_LOCATION_EXIST;
                        }
                    }
                    catch (Exception ex)
                    {
                        response.isProcessSuccess = false;
                        response.errCode = ErrorCodes.CODE_ERR_INTERNAL_ERR;
                        response.errMsg = ex.Message;
                    }
                }
            }
            return response.ToJson();
        }

        [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public string catalogExists(string code)
        {
            ZKResponse response = new ZKResponse();
            string connStr = SqlConnectionManager.GetConnStrFromConfig();
            using (SqlConnection conn = SqlConnectionManager.CreateSqlConnection(connStr))
            {
                conn.Open();
                using (SqlCommand cmd = SqlCommandManager.Create(conn, CommandType.StoredProcedure))
                {
                    cmd.CommandText = "proc_catalog_existence_check";
                    cmd.Parameters.Add("@code", SqlDbType.NVarChar).Value = code;
                    cmd.Parameters.Add("@return", SqlDbType.Int).Direction = ParameterDirection.ReturnValue;
                    try
                    {
                        cmd.ExecuteNonQuery();
                        int returnVal = cmd.Parameters["@return"].Value.toInt32().Value;
                        if (returnVal > 0)
                        {
                            response.isProcessSuccess = false;
                            response.errCode = ErrorCodes.CODE_ERR_ON_CATALOG_CODE_EXISTS;
                            response.errMsg = ErrorMsgs.MSG_ERR_ON_CATALOG_CODE_EXISTS;
                        }
                    }
                    catch (Exception ex)
                    {
                        response.errCode = ErrorCodes.CODE_ERR_INTERNAL_ERR;
                        response.errMsg = ex.Message;
                    }
                }
            }
            return response.ToJson();
        }

        [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public string brandExists(string code)
        {
            ZKResponse response = new ZKResponse();
            string connStr = SqlConnectionManager.GetConnStrFromConfig();
            using (SqlConnection conn = SqlConnectionManager.CreateSqlConnection(connStr))
            {
                conn.Open();
                using (SqlCommand cmd = SqlCommandManager.Create(conn, CommandType.StoredProcedure))
                {
                    cmd.CommandText = "proc_brand_existence_check";
                    cmd.Parameters.Add("@code", SqlDbType.NVarChar).Value = code;
                    cmd.Parameters.Add("@return", SqlDbType.Int).Direction = ParameterDirection.ReturnValue;
                    try
                    {
                        cmd.ExecuteNonQuery();
                        int returnVal = cmd.Parameters["@return"].Value.toInt32().Value;
                        if (returnVal > 0)
                        {
                            response.isProcessSuccess = false;
                            response.errCode = ErrorCodes.CODE_ERR_ON_BRAND_CODE_EXISTS;
                            response.errMsg = ErrorMsgs.MSG_ERR_ON_BRAND_CODE_EXISTS;
                        }
                    }
                    catch (Exception ex)
                    {
                        response.errCode = ErrorCodes.CODE_ERR_INTERNAL_ERR;
                        response.errMsg = ex.Message;
                    }
                }
            }
            return response.ToJson();
        }
    }
}
